package com.auhaix.Utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.DecimalFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author: Auhaix
 * E-mail: xh@qiandw.com
 * Description:
 * CreatedTime: 2017/8/3 10:57
 * Modified by:
 */
public class StringUtils {
    /**
     * 手机号正则表达式
     */
    private static final String PHONE_REGEXP = "^(13[0-9]|14[579]|15[0-3,5-9]|17[0135678]|18[0-9])\\d{8}$";
    private static DecimalFormat decimalFormat = new DecimalFormat("#0.00");

    /**
     * 将List转为字符串
     *
     * @param list
     * @return
     */
    public static String listToString(List<String> list) {
        StringBuffer stringBuffer = new StringBuffer();
        String result = "";
        if (null != list) {
            for (String str : list) {
                stringBuffer.append(str + ",");
            }
            result = stringBuffer.toString();
            if (result.endsWith(",")) {
                result = result.substring(0, result.length() - 1);
            }
        }
        return String.format("[%s]", result);
    }

    /**
     * 判断给定的字符串是否是手机号
     *
     * @param mobile
     * @return
     */
    public static boolean isMobile(String mobile) {
        if (org.springframework.util.StringUtils.isEmpty(mobile)) {
            return false;
        } else {
            Pattern pattern = Pattern.compile(PHONE_REGEXP);
            Matcher matcher = pattern.matcher(mobile);
            return matcher.matches();
        }
    }

    /**
     * 判断给定的字符串是否是数字
     *
     * @param numberStr
     * @return
     */
    public static boolean isNumber(String numberStr) {
        if (org.springframework.util.StringUtils.isEmpty(numberStr)) {
            return false;
        } else {
            Pattern pattern = Pattern.compile("[0-9]*");
            Matcher matcher = pattern.matcher(numberStr);
            return matcher.matches();
        }
    }

    /**
     * 格式化double数据，保留两位小数
     *
     * @param doubleValue
     * @return
     */
    public static String formatDouble(double doubleValue) {
        return decimalFormat.format(doubleValue);
    }

    /**
     * 将传入的对象转换为字符串形式
     *
     * @param objectMapper
     * @param value
     * @return
     */
    public static String getStringFormatValueOfObject(ObjectMapper objectMapper, Object value) {
        try {
            return objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            return "convert to string error!";
        }
    }
}
